//ajax请求  
function ajaxRequest(obj) { 
    //获取平台类型并
    if(!$api.getStorage("platform")){
        console.log("获取platform并存起来=======:"+api.systemType);
        $api.setStorage("platform", api.systemType);
    }
    var platform = $api.getStorage("platform");
    obj.platform = platform;
    
    api.accessNative({
        name: 'getToken',
        extra: {
            key: 'value'
        }
    }, function(ret, err) {
        //alert('客户端来的token=='+JSON.stringify(ret));
        if (ret) {
            obj.token = JSON.stringify(ret);
            $api.setStorage("token", JSON.stringify(ret));
            ajax(obj);
        } else {
            obj.token = "";
            ajax(obj);
        }
    }); 
    //测试使用云修复时候注释
    setTimeout(function(){
        obj.token = "Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiIsImp0aSI6IjFlMDI2ZThhMzA3YjAzZjRmMDI5MjI2ZjdlMGMzMjViYjFmMWFjNmU5MTQ1ODVlOTY2OGQzZDQ4MmM1N2I2ZWEwMTU1MzM5ZGFlNGFmZjExIn0.eyJhdWQiOiIyIiwianRpIjoiMWUwMjZlOGEzMDdiMDNmNGYwMjkyMjZmN2UwYzMyNWJiMWYxYWM2ZTkxNDU4NWU5NjY4ZDNkNDgyYzU3YjZlYTAxNTUzMzlkYWU0YWZmMTEiLCJpYXQiOjE1MzU0MjExMDMsIm5iZiI6MTUzNTQyMTEwMywiZXhwIjoxNTY2OTU3MTAzLCJzdWIiOiIxMTMwNzgiLCJzY29wZXMiOltdfQ.UPVWU59uictRzCpegDdhxfiqMWAXzesRfLHyJzKpMPn2yuS_NaF6PVM5zxHtiCGHJZ1dQyVPFrOrMcbhbHoTPbKcJDMY6QAxbO_2LrZZaqmnE-FMo2fiMHbUC-7YDiY3is2aHz4rl_NuR1BQDODUIyD68EZ7_7-mpsidjkOAAQwgijxmhgngHpVQVnTkgBppEMQM29ilSAhFuBZBhtV3qwzB5QNC7oLgVwMx4synYMAGcD0hO05rkYRmVnG6oUgxDlOYrnZi1cJGRzGNHKBFopWqZWNs78y7xNEphJ0WmxaVlJByJ4pOk6e-4nUP4IGyg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E-fI12KFNegBCT7uzGq4QSaCxHcxcnmmlCpefdaPYkUY4f6crpw4LRGxoEllZgAt6-1dNBNGdWO4k4vlBgnfomjIlkrGhi2gGzQ8EZMK6LOzAl4aGFqkWARC-OOWI7YwwRML92CdPGg11zwxcSF1YOZbCzVfCKDIOKgG48HBUtf_qtf5QlhJgcdyZtKEiKrAqcSsqb811UbF1eIhEFMe7svvwy2orCQL45Rpevf1t9KMWGifWj9BAgH68W_DZAeGxd0BGjXrJPYBTZuh_Aai8arLe4b3ZPdgEISG3C5MjZMSQzry_KEA66iCYIJzbANMyKQpMcTe5py5Vx0wbVI4iDVOQKJhk8dt_KhtykmWhE1AyVjSTNMNuC80HO9XnRuHZs"
        $api.setStorage("token", obj.token);
        ajax(obj);
    },1000)
} 

//获取浏览器的参数
function getQueryString(name) {
  return decodeURIComponent((new RegExp('[?|&]'+name+'='+'([^&;]+?)(&|#|;|$)').exec(location.href)||[,""])[1].replace(/\+/g,'%20'))||null;
}

function ajax(obj){
    if(obj.isShowprog){
        api.showProgress({
            title: '努力加载中...',
            text: '先喝杯茶...',
            modal: false
        });
    }
    api.ajax({  
        url: 'https://tbb.gvgcn.com/' + obj.url,  
        //url: 'http://192.168.1.184:8025/' + obj.url,  
        method: obj.method || 'get',  
        cache: false,  
        timeout: 5,  
        dataType: 'json',  
        headers:{
            'Content-Type':'application/json',
            'Authorization':obj.token,
            'Platform':'h5'//obj.platform
        },  
        data: {
            body: obj.data || {}
        } 
    }, function(ret, err) { 
        //alert('11111='+JSON.stringify(ret));
        //alert('22222='+JSON.stringify(err));
        api.hideProgress();
        if(err){
            if (err.statusCode != "200") {
                mytoast(err.body.info)
                if(obj.errcallback){
                    obj.errcallback(err.body);
                }
            }
        }else{
            obj.callback(!ret?'':ret);  
        }
    });
}

//获取封装api.toast  
function mytoast(msg, str_area) { 
    if(msg){
        api.toast({  
            msg: msg,  
            duration: 3000,  
            location: str_area || 'bottom'  
        });  
    } 
}  

//打开新窗口 dirAndName   ../dir/winname  
//checklogin: 1:需要登录才能打开  0:不需要登录就打开  
function openNewWin(winObj) {  
    winObj.checklogin = winObj.checklogin || 0; 
    //判断是否有登陆  
    if (winObj.checklogin) {  
        if (!isLogin()) {  
            mytoast("请先登录！")
            api.openWin({  
                name: 'login',  
                url: "./../html/login.html",  
            });  
            return false;  
        }  
    }  
  
    //拆分得到winows name    
    api.openWin({  
        name: winObj.name,  
        url: winObj.name + '.html'+ (winObj.urlParam || ''),  
        bounces: false,  
        pageParam:winObj.params || {}  
    });  
}

function closeWin(winName) { 
	if(winName){
	    api.closeWin({
		    name: winName,
		}); 
	}else{
		api.closeWin();
	}
}

function openNewFrame(frameObj) { 
    api.openFrame({
	    name: frameObj.name,
	    url: "./"+frameObj.name+'.html',
	    rect: frameObj.rect || {
	        x: 0,
	        y: 0,
	        w: 'auto',
	        h: 'auto'
	    },
	    pageParam: frameObj.params || {},
	    bounces: true
	}); 
}

function closeFrame(frameName) { 
	if(frameName){
	    api.closeFrame({
		    name: frameName,
		}); 
	}else{
		api.closeFrame();
	}
}

function dateFtt(fmt,mytime){ //author: meizz  
	var date = new Date(parseInt(mytime));  
	var o = {  
	    "M+" : date.getMonth()+1,                 //月份  
	    "d+" : date.getDate(),                    //日  
	    "h+" : date.getHours(),                   //小时  
	    "m+" : date.getMinutes(),                 //分  
	    "s+" : date.getSeconds(),                 //秒  
	    "q+" : Math.floor((date.getMonth()+3)/3), //季度  
	    "S"  : date.getMilliseconds()             //毫秒  
	};  
	if(/(y+)/.test(fmt))  
	    fmt=fmt.replace(RegExp.$1, (date.getFullYear()+"").substr(4 - RegExp.$1.length));  
	for(var k in o)  
	    if(new RegExp("("+ k +")").test(fmt))  
	  fmt = fmt.replace(RegExp.$1, (RegExp.$1.length==1) ? (o[k]) : (("00"+ o[k]).substr((""+ o[k]).length)));  
	  return fmt;  
}  
  
//判断是否登录  
function isLogin() {  
    var currendToken= $api.getStorage('token');  
    if ( typeof(currendToken) != undefined && typeof(currendToken) != 'undefined' && currendToken != null) {  
        console.log("--------------------------------已经登录----------------------");  
        return true;  
    } else {  
        console.log("--------------------------------没有登录----------------------");  
        return false;  
    }  
} 

//云修复静默方式监听
function smartupdatefinish(){
    api.addEventListener({
        name:'smartupdatefinish'
    }, function(ret, err){  
        mytoast('云修复完成,为您重启APP');
        api.rebootApp();
    });
}

//无网络...  
function notOnLine(str,callback) {  
    var onlineBox = $api.byId('notOnLine');  
    var path = "widget://res/nowifi-png.txt";  
    var fs = api.require('fs');  
    var urls = api.readFile({  
        sync: true,  
        path: path  
    });  
    var html = '<div class="cf-font2" id="notOnLine"><div class="notice clearfix" onclick="javascript:' + callback + '"><img src="'+urls+'" \/><div class="aui-font-size-14" style="color:#D1D2D4"  >网络异常、点击重新加载<\/div><\/div><\/div>';  
    if (str) {  
        console.log('callback' + callback);  
        if (!onlineBox){  
            $api.append(document.body, html);  
        }  
        var onlineBox = $api.byId('notOnLine');  
        onlineBox.style.display = 'block';  
        onlineBox.addEventListener('touchmove',gundongEvent);  
        //隐藏loading框  
        loadingFullScreen(false);  
    } else {  
        if(onlineBox){  
          onlineBox.style.display = 'none';  
        }  
    }  
} 

function loading(bool){
    var bool = bool;
    var html = '<div style="height: 100%;" id="loading">'+
        '<div class="center absolute" style="top: 40%;left: 50%;margin-left: -22px;z-index: 1000;">'+
            '<svg class="loading" width="44px" height="44px" viewBox="0 0 44 44">'+
                '<circle class="path" fill="none" stroke-width="4" stroke-linecap="round" cx="22" cy="22" r="20"></circle>'+
            '</svg>'+
        '</div>'+
        '<div class="loading-bg fixed" :style="style"></div>'+
    '</div>';
    var loading = $api.byId('loading');
    //alert(loading+'bool=='+bool);
    if(bool){
        if(loading){
            loading.style.display = 'block'; 
        }else{
            $api.append(document.body, html); 
        }
    }else{
        if(loading){
            loading.style.display = 'none'; 
        }
    }
}
//统一处理返回上一页窗口（关闭当前页）
/*console.log($api.domAll('.back').length+"=====");
$api.addEvt($api.domAll('.back'), 'click', function(){
   closeWin();
});*/